<?php

/**
 * 函数库
 * ============================================================================
 * TBlog TBlog博客系统　BY Tmac PHP MVC framework
 * $Author: zhangwentao $  <zwttmac@qq.com>
 * $Id: Functions.class.php 1582 2011-03-11 10:56:52Z zhangwentao $
 * http://www.t-mac.org；
 */
class Functions
{

    /**
     * 获取客户端IP地址
     * @return <type>
     */
    static function get_client_ip()
    {
        if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown"))
            $ip = getenv("HTTP_CLIENT_IP");
        else if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown"))
            $ip = getenv("HTTP_X_FORWARDED_FOR");
        else if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown"))
            $ip = getenv("REMOTE_ADDR");
        else if (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown"))
            $ip = $_SERVER['REMOTE_ADDR'];
        else
            $ip = "unknown";
        return($ip);
    }

    /**
      +----------------------------------------------------------
     * 字符串截取，支持中文和其他编码
      +----------------------------------------------------------
     * @static
     * @access public
      +----------------------------------------------------------
     * @param string $str 需要转换的字符串
     * @param string $length 截取长度
     * @param string $start 开始位置
     * @param string $charset 编码格式
     * @param string $suffix 截断显示字符
      +----------------------------------------------------------
     * @return string
      +----------------------------------------------------------
     */
    static function msubstr($str, $length, $start=0, $charset="utf-8", $suffix=true)
    {
        if (function_exists("mb_substr"))
            return mb_substr($str, $start, $length, $charset);
        elseif (function_exists('iconv_substr')) {
            return iconv_substr($str, $start, $length, $charset);
        }
        $re['utf-8'] = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
        $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
        $re['gbk'] = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
        $re['big5'] = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
        preg_match_all($re[$charset], $str, $match);
        $slice = join("", array_slice($match[0], $start, $length));
        if ($suffix)
            return $slice . "…";
        return $slice;
    }

    /**
     * 截取中文字符串
     * Utf-8、gb2312都支持的汉字截取函数
     * cut_str(字符串, 截取长度, 开始长度, 编码);
     * 编码默认为 utf-8
     * 开始长度默认为 0
     */
    function cut_str($string, $sublen, $start = 0, $code = 'UTF-8')
    {
        if ($code == 'UTF-8') {
            $pa = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xef][\x80-\xbf][\x80-\xbf]|\xf0[\x90-\xbf][\x80-\xbf][\x80-\xbf]|[\xf1-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]/";
            preg_match_all($pa, $string, $t_string);

            if (count($t_string[0]) - $start > $sublen)
                return join('', array_slice($t_string[0], $start, $sublen)) . "...";
            return join('', array_slice($t_string[0], $start, $sublen));
        }
        else {
            $start = $start * 2;
            $sublen = $sublen * 2;
            $strlen = strlen($string);
            $tmpstr = '';

            for ($i = 0; $i < $strlen; $i++) {
                if ($i >= $start && $i < ($start + $sublen)) {
                    if (ord(substr($string, $i, 1)) > 129) {
                        $tmpstr.= substr($string, $i, 2);
                    } else {
                        $tmpstr.= substr($string, $i, 1);
                    }
                }
                if (ord(substr($string, $i, 1)) > 129)
                    $i++;
            }
            if (strlen($tmpstr) < $strlen)
                $tmpstr.= "...";
            return $tmpstr;
        }
    }

    //GB转UTF-8编码
    static function gb2utf8($gbstr)
    {
        if (function_exists('iconv')) {
            return iconv('gbk', 'utf-8//ignore', $gbstr);
        }
        global $CODETABLE;
        if (trim($gbstr) == "") {
            return $gbstr;
        }
        if (empty($CODETABLE)) {
            $filename = DEDEINC . "/data/gb2312-utf8.dat";
            $fp = fopen($filename, "r");
            while ($l = fgets($fp, 15)) {
                $CODETABLE[hexdec(substr($l, 0, 6))] = substr($l, 7, 6);
            }
            fclose($fp);
        }
        $ret = "";
        $utf8 = "";
        while ($gbstr != '') {
            if (ord(substr($gbstr, 0, 1)) > 0x80) {
                $thisW = substr($gbstr, 0, 2);
                $gbstr = substr($gbstr, 2, strlen($gbstr));
                $utf8 = "";
                @$utf8 = u2utf8(hexdec($CODETABLE[hexdec(bin2hex($thisW)) - 0x8080]));
                if ($utf8 != "") {
                    for ($i = 0; $i < strlen($utf8); $i += 3)
                        $ret .= chr(substr($utf8, $i, 3));
                }
            } else {
                $ret .= substr($gbstr, 0, 1);
                $gbstr = substr($gbstr, 1, strlen($gbstr));
            }
        }
        return $ret;
    }

    static function GetHttps($url, $charset = "utf-8")
    {
        if (function_exists('file_get_contents')) {
            $file_contents = @file_get_contents($url);
        } else {
            $ch = curl_init();
            $timeout = 5;
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
            $file_contents = curl_exec($ch);
            curl_close($ch);
        }
        if ($charset == "utf-8") {
            return $file_contents;
        } elseif ($charset == "gb2312") {
            $file_contents = iconv("gb2312", "UTF-8", $file_contents);
            return $file_contents;
        }
    }

    //创建目录 递归创建多级目录
    static function CreateFolder($filedir)
    {
        if (!file_exists($filedir)) {
            if (!self::CreateFolder(dirname($filedir))) {
                return false;
            }
            if (!mkdir($filedir, 0777)) {
                return false;
            }
        }
        return true;
    }
    
    /**
     * 替换url链接
     */
    static function replace_for_mod_rewrite()
    {
        global $cfg_rewrite, $cfg_rewrite_search, $cfg_hotel_info;
        if (empty($cfg_rewrite)) {
            return;
        }
        $content = ob_get_contents();
        $urlin = array(
            "/index.php\?m=([a-zA-Z0-9_]*)(['|\"])/", //以a为链接"或'或结尾来识别一位的链接
            "/index.php\?m=weather&cityid=([0-9]*)&xid=([0-9]*)/", //index.php?m=weather&cityid=321&xid=622
            "/index.php\?m=news&class_id=([0-9]*)&page=([0-9]*)/",
            "/index.php\?m=news&class_id=([0-9]*)/",
            "/index.php\?m=liansuohotel&cityid=([0-9]*)&chain_id=([0-9]*)/", //liansuohotel?cityid&chain_id|hotelinfo cityid&hotel_id
            "/index.php\?m=liansuohotel&([a-zA-Z_]+)=([0-9]*)/",
            "/index.php\?m=city&cityid=([0-9]*)/",
            "/index.php\?m=hotelinfo&cityid=([0-9]*)&hotel_id=([0-9]*)/",
            "/index.php\?m=hotelinfo&hotel_id=(['\+mData\[i\]\[0\]\+']{15})/", //'+mData[i][0]+'
            "/index.php\?m=hotelinfo&hotel_id=([0-9]*)/",
            "/index.php\?m=(comment|question|weather|searchlist)&cityid=([0-9]*)&page=([0-9]*)/", //comment,question index.php?m=queston&cityid=53&page=2
            "/index.php\?m=hotellist&cityid=([0-9]*)&([\w%]*)/", //index.php?m=hotellist&cityid=53&rank=0&key=
            "/index.php\?m=(comment|question|weather|map|hotellist|searchlist)&cityid=([0-9]*)/",
            "/index.php\?m=(newsinfo|lable)&([a-zA-Z_]+)=([0-9]*)(['|\"])/",
//            "/index.php\?m=([a-zA-Z_]+)&([a-zA-Z_]+)=([0-9]*)&page=([0-9]*)/",
            "/index.php\?m=([^[news])&page=([0-9]*)/", //news index.php?m=news&page=2
            "/index.php\?m=lable&cityid=([0-9]*)&classid=([0-9]*)&page=([0-9]*)/", //index.php?m=lable&cityid=321&classid=0&page=2
            "/index.php\?m=lable&(pid|cityid)=([0-9]*)&classid=([0-9]*)/", //index.php?m=lable&pid=32&classid=0
            "/index.php\?m=(hotelmap|hotelcomment|hotelnearby|hotelpicture|hotelquestion|hotellable)&hotel_id=([0-9]*)/", //index.php?m=hotelmap&hotel_id=3937
//            "/index.php\?m=hotellist&([\w]*)=([0-9]*)&([\w]*)=([\w%]*)&([\w]*)=([\w%]*)/", //index.php?m=hotellist&cityid=53&rank=0&key=
        );
        $urlout = array(
            "$1.html$2",
            "weather-$1-$2.html",
            "news-c$1-$2.html",
            "news-c$1.html",
            "liansuo-$1-$2.html", //5
            "liansuo-$1-$2.html",
            "city-$1.html",
            "$cfg_hotel_info-$1-$2.html",
            "$cfg_hotel_info-$1.html",
            "$cfg_hotel_info-$1.html", //10
            "$1-$2-$3.html",
            "$cfg_rewrite_search-$1.html?$2", //hotellist
            "$1-$2.html",
            "$1-$3.html$4",
//            "$1-$3-$4.html",
            "$1-$2.html", //15
            "lable-cityid$1-$2-$3.html",
            "lable-$1$2-$3.html",
            "$1-$2.html",
//            "$cfg_rewrite_search-$1$2-$3$4-$5$6.html", //hotellist
        );
        $s = preg_replace($urlin, $urlout, $content);
        ob_end_clean();
        //上面clean后再次开启压缩
        if ($GLOBALS['TmacConfig']['Common']['gzip']) {
            function_exists('ob_gzhandler') ? ob_start('ob_gzhandler') : ob_start();
        } else {
            ob_start();
        }

        echo $s;
    }

}